package timer;

/**
 * @author Created by chenxin34 on 2018/4/15 下午9:39.
 */

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 线程池测试类
 *
 * @author lincanhan
 */
public class ScheduledExecutorServiceTest {
    private static long diff = 0;
    private static int count = 0;

    public static void main(String[] args) throws Exception {
        testScheduleDelay();

        Thread.sleep(20000);
        System.out.println("all=" + count);
        System.out.println(diff);
    }

    public static void testScheduleDelay() {
        System.out.println(new Date());
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
        scheduledExecutorService.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("delay 0s");
                System.out.println(new Date());
            }
        }, 0, TimeUnit.SECONDS);

        scheduledExecutorService.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("delay 10s");
                System.out.println(new Date());
            }
        }, 10, TimeUnit.SECONDS);
    }

    public static void schedule() {
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        for (int i = 0; i < 10000; i++) {
            WorkerThread workerThread = new WorkerThread("task:" + i, 1000);
            scheduledExecutorService.schedule(workerThread, 1, TimeUnit.SECONDS);
            if (i % 100 == 0) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 工作任务
     */
    static class WorkerThread implements Runnable {
        private String command;
        private final long delay; //延迟时间
        private final long expire;  //到期时间
        public WorkerThread(String s, long delay) {
            this.delay = delay;
            expire = System.currentTimeMillis() + delay;    //到期时间 = 当前时间+延迟时间
            this.command = s;
        }
        @Override
        public void run() {
            if (command.equals("task:151")){
                throw new RuntimeException("task101 ex");
            }
            long current = System.currentTimeMillis();
            System.out.println(command + ",current=" + current + "，expire=" + expire);
            diff += Math.abs(current - expire);
            count++;
        }
        private void processCommand() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        @Override
        public String toString() {
            return this.command;
        }
    }
}
